﻿using System;
using System.Collections.Generic;

class LargestNumberInArrayLowerThanK
{
    static void Main()
    {
        int numberFound = int.MinValue;
        Console.WriteLine("Enter the dimention of the array:");
        int dimention = int.Parse(Console.ReadLine());
        int[] arrayOfInts = new int[dimention];
        for (int index = 0; index < dimention; index++)
        {
            Console.WriteLine("Enter element {0}", index);
            arrayOfInts[index] = int.Parse(Console.ReadLine());
        }
        Console.WriteLine();
        Console.WriteLine("The array you entered is:");
        for (int i = 0; i < dimention; i++)
        {
            Console.Write("{0,3}",arrayOfInts[i]);      
        }
        Console.WriteLine();
        Console.WriteLine("The sorted array is:");
        Array.Sort(arrayOfInts);
        for (int i = 0; i < dimention; i++)
        {
            Console.Write("{0,3}", arrayOfInts[i]);
        }
        Console.WriteLine();
        Console.WriteLine("Enter a number K:");
        int numberK = int.Parse(Console.ReadLine());
        if (arrayOfInts[0] > numberK)
        {
            Console.WriteLine("There is no number <= K in this array!");
        }
        else
        {
            for (int j = 1; j < dimention; j++)
            {
                int elementIndex = Array.BinarySearch(arrayOfInts, numberK);
                
                if (elementIndex >= 0)
                {
                    numberFound = arrayOfInts[elementIndex];
                }
                else
                {
                    numberFound = arrayOfInts[~elementIndex - 1];
                }
            }
            Console.WriteLine(numberFound);
        }
    }
}

